package production.practice.common.init;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.*;

@Component
@Slf4j
public class EsBaseInitByDataBase implements SmartLifecycle {
    private volatile boolean running = false;


    private Integer pageSize=1000;
    private ExecutorService executor = Executors.newFixedThreadPool(10);

    @Override
    public void start() {
        long startTime=System.currentTimeMillis();
        if (!running) {
            try {
                log.info("开始初始化ES中的数据");
//                int total = Math.toIntExact(goodsMapper.selectCount(null));
                //todo 计算total的数目,mysqlMapper.selectCount(null)
                int total = 1000;
                int totalPages = (total + pageSize - 1) / pageSize;
                CountDownLatch latch = new CountDownLatch(totalPages);

                for (int pageNum = 1; pageNum <= totalPages; pageNum++) {
                    int finalPageNum = pageNum;
                    executor.submit(() -> {
                        try {


                        } finally {
                            latch.countDown();
                        }
                    });
                }

                latch.await();
                executor.shutdown();
                running = true;
                log.info("ES数据初始化完成");
                log.info("线程池初始化ES数据耗时： {}ms",System.currentTimeMillis() - startTime);

            } catch (InterruptedException e) {
                log.error("初始化ES数据失败", e);
            }
        }
    }



    @Override
    public void stop() {
        if (running) {
            log.info("开始清除ES中的数据");
            try {
                //todo 清楚ES中的数据   es.deleteAll();
                log.info("ES数据清除完成");
            } catch (Exception e) {
                log.error("清除ES数据时发生异常", e);
            }
            running = false;
        }
    }

    @Override
    public boolean isRunning() {
        return running;
    }

    @Override
    public int getPhase() {
        return Integer.MAX_VALUE - 1; // 确保在ES客户端之后关闭
    }
}
